package com.bgs.engineering.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.bgs.engineering.annotation.GenerateUUID;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * @author 王宏
 * @version 1.0.0
 * @title MyMetaObjectHandler
 * @description <TODO description class purpose>
 * <p></p>
 * @creat 2023/5/11 20:24 Thursday
 **/
@Component
@Configuration
public class MyMetaObjectHandler implements MetaObjectHandler {
  @Override
  public void insertFill(MetaObject metaObject) {
    Object originalObject = metaObject.getOriginalObject();
    try {
      Class clazz = originalObject.getClass();
      for (Field declaredField : clazz.getDeclaredFields()) {
        declaredField.setAccessible(true);
        if (declaredField.isAnnotationPresent(GenerateUUID.class) && declaredField.get(originalObject) == null) {
          this.setFieldValByName(declaredField.getName(), IdWorker.get32UUID(), metaObject);
        }
      }
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } finally {
      this.setFieldValByName("createTime", new Date(), metaObject);
      this.setFieldValByName("updateTime", new Date(), metaObject);
    }
  }

  @Override
  public void updateFill(MetaObject metaObject) {
    this.setFieldValByName("updateTime", new Date(), metaObject);
  }
}
